<?php namespace App\Core\Repository;

trait Criteriable{
    
    protected $criterias = [];
    
    public function resetCriteria($withGlobal = false){
        foreach($this->criterias as $key => $criteria){
            if(!$criteria->isGlobal() || $withGlobal){
                unset($this->criterias[$key]);
            }
        }
        return $this;
    }

    public function addCriteria(Criteria $criteria, $name = '', $global = false){
        if($name){
            $criteria->setName($name);
        }
        if($global){
            $criteria->enGlobal();
        }
        $this->removeCriteria($criteria->getName());
        $this->criterias[] = $criteria;
        return $this;
    }
    
    public function addCriterias(array $criterias){
        foreach($criterias as $name => $criteria){
            $this->addCriteria($criteria, !is_numeric($name) ? $name : '');
        }
        return $this;
    }
    
    public function removeCriteria($name){
        foreach($this->criterias as $key => $item){
            if($item->getName() == $name){
                unset($this->criterias[$key]);
            }
        }
        return $this;
    }

    public function applyCriterias(){
        foreach ($this->criterias as $criteria) {
            if(!$criteria instanceof Criteria){
                throw new \Exception('parameter not validated');
            }
            /*if($criteria->applyed){
                continue;
            }*/
            $criteria->apply($this);
        }
        return $this;
    }
    
    public function getCriterias(){
        return $this->criterias;
    }
    
    public function setCriterias(Array $criterias){
        $this->criterias = $criterias;
        return $this;
    }
}